package servlets;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import classes.HomeworkManagerLecturer;

/**
 * Servlet implementation class addHomework
 */
@WebServlet("/addHomework")
public class addHomework extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public addHomework() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String filename = "";
		PrintWriter out = response.getWriter();

		String homework_Name = "";
		String start_date = "";
		String deadline = "";
		int group_id = 0;
		String groupName = "";
		String subject = "";

		try {

			String url = "C:\\Users\\Davidlek\\workspace\\Project\\HomeWorkManager\\WebContent\\StudentHomework\\";
			boolean empty = false;
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// Process regular form field (input
					// type="text|radio|checkbox|etc", select, etc).
					String fieldname = item.getFieldName();
					String fieldvalue = item.getString();
					if (fieldname.equals("homeworkname")) {
						homework_Name = fieldvalue;
					} else if (fieldname.equals("start_date")) {
						start_date = fieldvalue;
					} else if (fieldname.equals("deadline")) {
						deadline = fieldvalue;
					} else if (fieldname.equals("group_id")) {
						group_id = Integer.parseInt(fieldvalue);
					} else if (fieldname.equals("groupName")) {
						groupName = fieldvalue;
					} else if (fieldname.equals("subject")) {
						subject = fieldvalue;
					}
				} else {
					// Process form file field (input type="file").
					String fieldname = item.getFieldName();
					filename = FilenameUtils.getName(item.getName());
					if (filename.isEmpty()) {
						out.println("you havent choosed file to upload. please ");
						out.println("<a href=\"addSubject.jsp\">try again.</a>");
						out.println("<br>");
						empty = true;
					} else {

						InputStream filecontent = item.getInputStream();
						url += filename;
						filename = url;
						FileOutputStream fos = new FileOutputStream(url);
						int i;
						while ((i = filecontent.available()) > 0) {
							byte[] b = new byte[i];
							filecontent.read(b, 0, b.length);
							fos.write(b);
						}
						filecontent.close();
						fos.flush();
						fos.close();
					}
				}
			}

		} catch (FileUploadException e) {
			throw new ServletException("Cannot parse multipart request.", e);
		}

		HomeworkManagerLecturer hmanager = (HomeworkManagerLecturer) getServletContext()
				.getAttribute(HomeworkManagerLecturer.HOMEWORKMANAGERLECTURER);
		hmanager.createHomework(homework_Name, group_id, start_date, deadline,
				filename);
		RequestDispatcher dispatch = request
				.getRequestDispatcher("homeworks.jsp?groupName=" + groupName
						+ "&subject=" + subject);
		dispatch.forward(request, response);
	}
}
